package com.haotian;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

import com.alibaba.druid.pool.DruidDataSource;
import com.haotian.dataconvert.Dto;
import com.haotian.db.jdbc._DBConnectionPool;
import com.haotian.db.jdbc._JdbcTemplate;
import com.haotian.db.jdbc.druid._DruidConnectionPool;
import com.haotian.redis.basic._RedisQueue;
import com.haotian.redis.config._RedisConfig;

import redis.clients.jedis.HostAndPort;

public class Application {
	/**
	 * <p></p>
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("欢迎使用昊天工具包 ， 工具包目前支持功能如下：");
		Scanner sc = new Scanner(System.in);
		String no = null;
		try {
			System.out.println("1：redis连接测试");
			System.out.println("2：Mysql连接测试");
			System.out.print("请输入功能编号:");
			no = sc.nextLine();
			switch (no) {
			case "1":// redis 测试
				System.out.print("请输入redis地址与端口空格分隔：");
				String addr = sc.nextLine();
				String[] addrs = addr.split(" ");
				
				if (addrs.length != 2) {
					System.out.println("地址格式不正确");
				} else {
					Set<HostAndPort> nodes = new HashSet<>();
					nodes.add(new HostAndPort(addrs[0], Integer.valueOf(addrs[1])));
					_RedisConfig config = new _RedisConfig();
					System.out.print("请输入密码:");
					String password = sc.nextLine();
					config.setMaxIdle(2);
					config.setMaxTotal(5);
					config.setMaxWaitMillis(30000);
					config.setTestOnBorrow(true);
					config.setTestOnReturn(true);
					config.setTestWhileIdle(true);
					final _RedisQueue queue = new _RedisQueue(nodes, password, 30000, config);
					System.out.println(System.lineSeparator() + queue.ping());
				}
				break;
			case "2":// mysql 测试
				System.out.print("请输入MYSQL连接URL字符串(请不要包含\\反斜杠,请使用/):");
				String uri = sc.nextLine();
				System.out.print("请输入用户名：");
				String username = sc.nextLine();
				System.out.print("请输入密码：");
				String password = sc.nextLine();
				// 创建数据源
				DruidDataSource ds = new DruidDataSource();
				/*
				 * 配置数据源 cluster 写法
				 * jdbc:mysql:loadbalance://127.0.0.1:33306/db_fastdfs?
				 * roundRobinLoadBalance=true&characterEncoding=UTF-8 直连写法
				 * jdbc:mysql://182.92.164.72:3306/cloudlinkinkaipiao?characterEncoding=UTF-8
				 * oVDdhhSHh#wtfhr8&BUnDCvQgd6H0*GY
				 */
				ds.setUrl(uri);
				ds.setDriverClassName("com.mysql.jdbc.Driver");
				ds.setUsername(username);
				ds.setPassword(password);
				ds.setFilters("wall");
				ds.setMaxActive(10);
				ds.setInitialSize(1);
				ds.setMinIdle(1);
				ds.setMaxWait(60000);
				ds.setUseUnfairLock(false);// true 为公平锁
				ds.setTimeBetweenEvictionRunsMillis(600000);
				ds.setMinEvictableIdleTimeMillis(300000);
				ds.setValidationQuery("SELECT 'x'");
				ds.setTestWhileIdle(true);
				ds.setTestOnBorrow(true);
				ds.setTestOnReturn(true);
				ds.setMaxOpenPreparedStatements(20);
				ds.setRemoveAbandoned(true);
				ds.setRemoveAbandonedTimeout(1800);
				ds.setLogAbandoned(true);

				// 创建druid 连接池
				_DBConnectionPool pool = new _DruidConnectionPool(ds);

				// 创建数据库操作模板
				final _JdbcTemplate jt = new _JdbcTemplate(pool);

				System.out.print("请输入执行语句（程序会自动判断查询与非查询操作SQL语句请小写）：");
				String sql = sc.nextLine();

				// 查询
				if (sql.indexOf("select") == 0) {

					List<Dto<String, Object>> queryForList = jt.queryForList(sql, new Object() {
					});
					System.out.println("结果如下:");
					for (Dto<String, Object> dto : queryForList) {
						Iterator<Entry<String, Object>> iterator = dto.entrySet().iterator();
						StringBuilder sb = new StringBuilder();
						for (; iterator.hasNext();) {
							Entry<String, Object> next = iterator.next();
							sb.append(next.getKey()).append(":").append(next.getValue()).append(",");
						}
						sb.setLength(sb.length() - 1);
						System.out.println(sb.toString());
					}

				} else {// 非查询
					int execute = jt.execute(sql, new Object() {
					});
					System.out.println("结果如下:");
					System.out.println(execute);
				}
				break;
			default:
				System.out.println("不存在的功能");
				break;
			}
		} catch (Exception e) {
			System.out.println("意外错误了 重来吧");
			e.printStackTrace();
		}finally {
			sc.close();
		}
	}
}
